import logging
from flask import Flask
from .custom_exceptions import ProcessManagerException, ConfigurationException
from dto.api_response import ApiResponseBuilder

logger = logging.getLogger(__name__)


def register_global_exception_handlers(app: Flask):
    """注册全局异常处理器"""

    @app.errorhandler(ProcessManagerException)
    def handle_process_manager_exception(e: ProcessManagerException):
        """处理进程管理器相关异常"""
        logger.warning(f"进程管理异常: {e.message}")
        response = ApiResponseBuilder.error(e.message, e.code)
        return response.to_json_response()

    @app.errorhandler(ConfigurationException)
    def handle_configuration_exception(e: ConfigurationException):
        """处理配置相关异常"""
        logger.error(f"配置异常: {e.message}")
        response = ApiResponseBuilder.error(e.message, e.code)
        return response.to_json_response()

    @app.errorhandler(404)
    def handle_not_found(error):
        """处理404异常"""
        logger.warning("API接口不存在")
        response = ApiResponseBuilder.not_found("API接口")
        return response.to_json_response()

    @app.errorhandler(500)
    def handle_internal_error(error):
        """处理500异常"""
        logger.error(f"服务器内部错误: {str(error)}")
        response = ApiResponseBuilder.internal_error()
        return response.to_json_response()

    @app.errorhandler(Exception)
    def handle_unexpected_exception(error):
        """处理未预期的异常"""
        logger.error(f"未预期的异常: {str(error)}", exc_info=True)
        response = ApiResponseBuilder.internal_error("系统发生未知错误")
        return response.to_json_response()